package com.jmpt.fangbohui.ui;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.TextView;
import cn.jpush.android.data.f;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.bean.NewHouseBean;
import com.jmpt.fangbohui.bean.NewHouseDetailBean;
import com.jmpt.fangbohui.bean.NewHouseDetailBean.Date_housetype_picEntity;
import com.jmpt.fangbohui.bean.NewHouseDetailBean.HouseInfoEntity;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.OldHouseDetailActivity.AppointHandler;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.ui.holder.HorizontalImageListHolder;
import com.jmpt.fangbohui.ui.holder.HouseDetailImagesHolder;
import com.jmpt.fangbohui.ui.holder.NewHouseRoomHolder;
import com.jmpt.fangbohui.ui.holder.NewListHolder;
import com.jmpt.fangbohui.ui.personalcenter.LoginActivity;
import com.jmpt.fangbohui.utils.DebugLog;
import com.jmpt.fangbohui.utils.TimeUtils;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.jmpt.fangbohui.utils.UIUtils;
import com.jmpt.fangbohui.view.MyAlertDialog;
import com.jmpt.fangbohui.view.wheelview.OnWheelChangedListener;
import com.jmpt.fangbohui.view.wheelview.ScreenInfo;
import com.jmpt.fangbohui.view.wheelview.WheelMain;
import com.jmpt.fangbohui.view.wheelview.WheelView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * @包名: com.jmpt.fangbohui.ui
 * @类名: NewHouseDetailActivity
 * @作者: China_Victor
 * @创建时间 : 2015-8-21 上午11:10:28
 * 
 * @描述: 新房详情
 */
public class NewHouseDetailActivity extends BaseHeadActivity implements OnWheelChangedListener {
	
	@ViewInject(R.id.fl_detail_images)
	private FrameLayout mFlImagesArea;
	
	@ViewInject(R.id.tv_new_detail_average_price)
	private TextView mTvAveragePrice;
	
	@ViewInject(R.id.tv_new_detail_open_time1)
	private TextView mTvOpenTime1;
	
	@ViewInject(R.id.tv_new_detail_address)
	private TextView mTvAddress;
	
	@ViewInject(R.id.tv_new_detail_tel)
	private TextView mTvTel;
	
	@ViewInject(R.id.tv_new_detail_open_time2)
	private TextView mTvOpenTime2;
	
	@ViewInject(R.id.tv_new_detail_staytime)
	private TextView mTvStaytime;
	
	@ViewInject(R.id.tv_new_detail_property_type)
	private TextView mTvPropertyType;
	
	@ViewInject(R.id.tv_new_detail_building_type)
	private TextView mTvBuildingType;
	
	@ViewInject(R.id.tv_new_detail_decorate)
	private TextView mTvDecorate;
	
	@ViewInject(R.id.tv_new_detail_area_ratio)
	private TextView mTvAreaRatio;
	
	@ViewInject(R.id.tv_new_detail_greening_rate)
	private TextView mTvGreeningRate;
	
	@ViewInject(R.id.tv_new_detail_carport)
	private TextView mTvCarport;
	
	@ViewInject(R.id.tv_new_detail_developers)
	private TextView mTvDevelopers;
	
	@ViewInject(R.id.tv_new_detail_property_company)
	private TextView mTvPropertyCompany;
	
	@ViewInject(R.id.fl_detail_house_type)
	private FrameLayout mFlHouseTypeArea;
	
	@ViewInject(R.id.fl_detail_house_news)
	private FrameLayout mFlHouseNewsArea;
	
	@ViewInject(R.id.fl_detail_house_rooms)
	private FrameLayout mFlHouseRoomsArea;
	
	private int houseId;
	private String houseName;
	
	public static final String HOUSE_ID = "house_id";
	public static final String HOUSE_TITLE = "house_name";
	
	private NewHouseDetailBean mDetailData;

	private WheelView yearWheelView;

	private WheelView monthWheelView;

	private WheelView dayWheelView;

	private WheelView hourWheelView;

	private WheelView minWheelView;

	private WheelMain wheelMain;

	private MyAlertDialog dialog;

	protected boolean dialogShow;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
		
		setContentView(R.layout.activity_new_house_detail);
		
		initHeadView();
		
		ViewUtils.inject(this);
		
		loadData();
	}

	private void initData() {
		Intent intent = getIntent();
		if(intent != null){
			houseId = intent.getIntExtra(HOUSE_ID, -1);
			houseName = intent.getStringExtra(HOUSE_TITLE);
		}
	}

	private void initHeadView() {
		// 设置标题
		showTitle(houseName);
		// 设置返回键
		showBackButton(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	public void refreshUI() {
		//刷新图片显示
		HouseDetailImagesHolder imagesHolder = new HouseDetailImagesHolder(this);
		imagesHolder.setData(mDetailData.getHouseImg());
		mFlImagesArea.addView(imagesHolder.getRootView());
		
		// 基本信息

		HouseInfoEntity houseInfoEntity = mDetailData.getHouseInfo();
		if(houseInfoEntity != null){
			setTitle(houseInfoEntity.getTitle());
			mTvAveragePrice.setText("均价" + houseInfoEntity.getJ_price() + "元/平");
			mTvOpenTime1.setText(houseInfoEntity.getOpentime());
			mTvAddress.setText(houseInfoEntity.getSales_addr());
			mTvTel.setText(houseInfoEntity.getTel());
			mTvOpenTime2.setText(houseInfoEntity.getOpentime());
			mTvStaytime.setText(houseInfoEntity.getOtherstime());
			mTvPropertyType.setText(houseInfoEntity.getWytype());
			mTvBuildingType.setText(houseInfoEntity.getJz_type());
			mTvDecorate.setText(houseInfoEntity.getJz_decorate());
			mTvAreaRatio.setText(houseInfoEntity.getRj_ratio() + "%");
			mTvGreeningRate.setText(houseInfoEntity.getLh_ratio() + "%");
			mTvCarport.setText(houseInfoEntity.getCar_num());
			mTvDevelopers.setText(houseInfoEntity.getDeveloper());
			mTvPropertyCompany.setText(houseInfoEntity.getWy_company());
		}
		
		//户型图
		{
			HorizontalImageListHolder houseTypeHolder = new HorizontalImageListHolder(this);
			houseTypeHolder.setData(getHouseTypeArrData());
			mFlHouseTypeArea.addView(houseTypeHolder.getRootView());
		}
		//新闻
		NewListHolder newListHolder = new NewListHolder(this);
		newListHolder.setData(mDetailData.getDate_newlist());
		mFlHouseNewsArea.addView(newListHolder.getRootView());
		//楼层
		NewHouseRoomHolder roomHolder = new NewHouseRoomHolder(this);
		roomHolder.setData(mDetailData.getDate_rooms());
		mFlHouseRoomsArea.addView(roomHolder.getRootView());

	}
	
	@OnClick(R.id.btn_appoint)
	public void appoint(View view){
		showDateOptionDialog("选择预约时间");
	}
	
	public void moreNews(){
		Intent intent = new Intent(this, NewsListActivity.class);
		intent.putExtra(NewsListActivity.NEWS_DATE, new Gson().toJson(mDetailData.getDate_newlist()));
		startActivity(intent);
	}
	
	public void moreRooms(){
		Intent intent = new Intent(this, RoomsListActivity.class);
		intent.putExtra(RoomsListActivity.ROOMS_DATE, new Gson().toJson(mDetailData.getDate_rooms()));
		startActivity(intent);
	}
	
	private String[][] getHouseTypeArrData() {
		List<Date_housetype_picEntity> houseTypePic;
		if(mDetailData != null && (houseTypePic = mDetailData.getDate_housetype_pic()) != null){
			String[][] arr = new String[2][houseTypePic.size()];
			String[] picArr = new String[houseTypePic.size()];
			String[] titleArr = new String[houseTypePic.size()];
			Date_housetype_picEntity picEntity;
			for (int i = 0; i < houseTypePic.size(); i++) {
				picEntity = houseTypePic.get(i);
				picArr[i] = picEntity.getHousetype_pic();
				titleArr[i] = picEntity.getName();
			}
			arr[0] = picArr;
			arr[1] = titleArr;
			return arr;
		}
		return null;
	}

	private void loadData() {
		addRequestHandle(ApiRequest.getNewHouseDetail(houseId, new HttpNewHouseDetailHandler(this)));
	}
	
	class HttpNewHouseDetailHandler extends JsonHttpHandler {

		public HttpNewHouseDetailHandler(Context context, boolean fromCache) {
			super(context, fromCache);
		}

		public HttpNewHouseDetailHandler(Context context) {
			super(context);
		}

		@Override
		public void onStart() {
			setShowProgressDialog("载入数据...");
			setProgressDialogCancleable(false);
			super.onStart();
		}
		
		@Override
		public void onCacheDo(String cache) {
			paseNewHouseDetail(cache);
		}

		@Override
		public void onDo(String response) {
			super.onDo(response);
			paseNewHouseDetail(response);
		}

		public void paseNewHouseDetail(String response) {
			try {
				mDetailData = new Gson().fromJson(response, NewHouseDetailBean.class);
				refreshUI();
			} catch (Exception e) {
				ToastHelper.ShowToast("数据有误,请稍后再试", UIUtils.getContext());
				e.printStackTrace();
			}
		}
	}
	
	/**
     * 选择时间对话框
     */
    private void showDateOptionDialog(String title) {
        LayoutInflater inflater = LayoutInflater.from(this);
        final View timepickerview = inflater.inflate(R.layout.timepicker,
                null);
        yearWheelView = (WheelView) timepickerview.findViewById(R.id.year);
        monthWheelView = (WheelView) timepickerview.findViewById(R.id.month);
        dayWheelView = (WheelView) timepickerview.findViewById(R.id.day);
        hourWheelView = (WheelView) timepickerview.findViewById(R.id.hour);
        minWheelView = (WheelView) timepickerview.findViewById(R.id.min);
        yearWheelView.addChangingListener(this);
        monthWheelView.addChangingListener(this);
        dayWheelView.addChangingListener(this);
        hourWheelView.addChangingListener(this);
        minWheelView.addChangingListener(this);
        minWheelView.setVisibility(View.GONE);
        ScreenInfo screenInfo = new ScreenInfo(this);
        wheelMain = new WheelMain(timepickerview, true);
        wheelMain.screenheight = screenInfo.getHeight();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        wheelMain.initDateTimePicker(year, month, day, h, 0);
        dialog = new MyAlertDialog(this)
                .builder()
                .setTitle(title)
                .setView(timepickerview)
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("确定", new View.OnClickListener() {
            @Override
			public void onClick(View v) {
				String selectStartTime = wheelMain.getTime() + ":00";
				if (!TimeUtils.timeAvaJudgeMet(TimeUtils.getCurrTime(), selectStartTime, 
						TimeUtils.TIME_TYPE_ALL)) {
					ToastHelper.ShowToast("日期选择不合理", getApplicationContext());
					return;
				}
				try {
					if (TimeUtils.parseToStandardForm(selectStartTime) != null) {
//						tv_startTime.setText(TimeUtils
//								.parseToStandardForm(selectStartTime));
						/** 修改时间后，进行数据刷新 */
						doAppoint(TimeUtils.parseToStandardForm(selectStartTime));
						
					}
				} catch (Exception e) {
					e.printStackTrace();
				}


            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialogShow = false;
            }
        });
        try {
            if (TimeUtils.parseToDayOFWeek(System.currentTimeMillis()) != null) {
                dialog.setDay(TimeUtils.parseToDayOFWeek(System.currentTimeMillis()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        dialog.show();
        dialogShow = true;

    }


	protected void doAppoint(String time) {
		// TODO Auto-generated method stub
		//ToastHelper.ShowToast(time, getApplicationContext());
		LoginBean loginBean = isLogin();
		if(loginBean != null){
			ApiRequest.personAppoint("yuyue", loginBean, houseId+"", time, new AppointHandler(this));
		}
	}

	public LoginBean isLogin() {
		LoginBean loginBean = new LoginSQLiteOperator(this).query();
		if(loginBean == null){
			//跳转到登录界面
			Intent loginIntent = new Intent(mContext,LoginActivity.class);
			mContext.startActivity(loginIntent);
			return null;
		}
		return loginBean;
	}
	
	class AppointHandler extends JsonHttpHandler {

		public AppointHandler(Context context) {
			super(context);
		}

		@Override
		public void onStart() {
			setShowProgressDialog("正在预约...");
			setProgressDialogCancleable(false);
			super.onStart();
		}

		@Override
		public void onDo(String response) {
			super.onDo(response);
			ToastHelper.ShowToastL("预约成功!稍后会有经纪人与您联系!", getApplicationContext());
		}

	}
	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (wheelMain != null && dialogShow) {
			if (dialog != null) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(sdf.parse(wheelMain.getTime() + ":00").getTime());
                    if (TimeUtils.parseToDayOFWeek(calendar.getTimeInMillis()) != null) {
                        dialog.setDay(TimeUtils.parseToDayOFWeek(calendar.getTimeInMillis()));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
		}
	}
	
}










